<template>
  <div class="login-layout">
    <el-card class="content">
      <div class="title">{{ mode === Mode.Login ? '登陆' : '注册' }}</div>

      <el-form
        v-if="mode === Mode.Login"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginFormRule"
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="loginForm.account" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" />
        </el-form-item>
        <el-button type="primary" @click="submitLoginFormForm">登陆</el-button>
        <el-button @click="toggleMode"> 切换到注册 </el-button>
      </el-form>

      <el-form
        v-else-if="mode === Mode.register"
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerFormRule"
      >
        <el-form-item label="名称" prop="nickname">
          <el-input v-model="registerForm.nickname" />
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="registerForm.account" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" />
        </el-form-item>
        <el-button type="primary" @click="submitRegisterForm">注册</el-button>
        <el-button @click="toggleMode"> 切换到登陆 </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { Mode } from './login.type'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { loginRequest, registerRequest } from './login.request'
import { useLoginForm, useRegisterForm } from './login.hooks'
import useUserStore from '@/store/user'

const mode = ref(Mode.Login)

const toggleMode = () => {
  mode.value = mode.value === Mode.Login ? Mode.register : Mode.Login
  loginFormRef.value?.resetFields()
  registerFormRef.value?.resetFields()
}

const { login } = useUserStore()

const { loginFormRef, loginForm, loginFormRule } = useLoginForm()

const router = useRouter()
const submitLoginFormForm = async () => {
  await loginFormRef.value?.validate()
  const {
    data: { token },
  } = await loginRequest(loginForm)

  login(token)
  ElMessage.success('登陆成功')

  setTimeout(() => {
    router.go(-1)
  }, 1000)
}

const { registerFormRef, registerFormRule, registerForm } = useRegisterForm()

const submitRegisterForm = async () => {
  await registerFormRef.value?.validate()
  await registerRequest(registerForm)
  ElMessage.success('注册成功请登陆')
}
</script>

<style scoped lang="less">
.login-layout {
  display: flex;
  align-items: center;
  height: 100vh;
  width: 100%;

  .content {
    margin: -100px auto 0;
    padding: 0 20px 10px;
    width: 500px;

    .title {
      margin-bottom: 20px;
      display: block;
      text-align: center;
    }
  }
}
</style>
